import React from 'react';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";
import MenuItem from 'react-bootstrap/lib/MenuItem';
import DropdownButton from 'react-bootstrap/lib/DropdownButton';
import Form from '../../src/component/formElement/Form.jsx';
import Label from '../../src/component/formElement/Label.jsx';
import Input from '../../src/component/formElement/Input.jsx';
import Selector from '../../src/component/formElement/Selector.jsx';
import SelectList from '../../src/component/formElement/SelectList.jsx';
import List from "../component/List.jsx";
import msgFrontAgent from  '../msgFrontAgent.js'

import HttpRequest from './../HttpRequest.js';

var PublishManagementTab = React.createClass({
    getInitialState: function () {
        return ({
            current_project: this.props.current_project,
            ListData: [], //配置数据
            ListItems: [], //左侧配置列表
            current_selected: null, //当前选中配置
            product_configs: []
        });
    },
    componentWillReceiveProps (newprops){
        this.setState({
            current_project: newprops.current_project
        }, function () {
            this.componentWillMount();
        });
    },
    componentWillMount: function () {
        HttpRequest.getAllPublishConfigs(this.state.current_project._id).success(function (configs) {
            if (configs.code != 500) {
                var listData = _.remove(configs.data, function (o) {
                    return o.project == this.state.current_project._id;
                }.bind(this));
                this.setState({
                    ListData: listData
                }, this._renderList)
            }
        }.bind(this)).error(function (err) {

        });
    },

    itemSelected: function (config) {

        HttpRequest.getPublishConfigById(config._id).success(function (res) {
            if (res.code == 500) {
                toastr.error(null,res.message);
            } else {
                this.setState({
                    current_selected: res.data
                });
            }
        }.bind(this)).error(function (err) {

        });

    },

    _renderList: function () {
        var items = [];
        this.setState({
            List: <List ListData={this.state.ListData}
                        ItemStyle={{cursor: "pointer"}}
                        SelectedItemStyle={{background:"#f3f3f3",cursor: "pointer"}}
                        onItemSelected={this.itemSelected}
                        itemDeleted={this.removePublishConfig}
                        ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有发布配置！ </span>}
                        deletable={false}
                        IconMap={[
                            {type:"mk",icon:<img src="/res/image/MK_h.png" />},
                            {type:"app",icon:<img src="/res/image/iphone_h.png" />},
                            {type:"app_plugin",icon:<i className="fa fa-plug" style={{fontSize:"23px"}} aria-hidden="true"/>}
                        ]}
            />
        });
        if (this.state.ListData.length > 0) {
            this.setState({
                current_selected: this.state.ListData[this.state.ListData.length - 1]
            })
        }
    },
    render: function () {

        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>发布配置</span>
                    <div style={{overflowY:"auto",height:"100%",maxHeight:"90%",marginTop:"5px"}}>
                        {this.state.List}
                    </div>

                </div>

                <div className="content_pageRight" style={{paddingLeft:"0px"}}>
                    <span className="info_title" style={{marginLeft:"30px"}}>发布历史</span>
                    <div style={{width:"100%",height:"calc(100% - 63px)",marginTop: "20px"}}>
                        <PublishRec current_selected={this.state.current_selected}
                                    current_project={this.state.current_project}
                        />
                    </div>
                </div>

            </div>
        )
    }
});
export default PublishManagementTab;

var PublishRec = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            current_project: this.props.current_project,
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project,
            publishInfo: [],
            publishRec: <div></div>,
        }, function () {
            this.componentWillMount();
        });
    },

    componentWillMount: function () {
        var thisOb = this;
        if (thisOb.state.current_selected) {
            HttpRequest.getPublishRec(thisOb.state.current_selected._id).success(function (resp) {
                if (resp.code == 500) {
                    toastr.error(null,"获取发布历史失败");
                } else {
                    thisOb.setState({
                        publishInfo: resp.data
                    }, function () {
                        thisOb.renderPublishRec()
                    });
                }
            }).error(function (error) {
                toastr.error(null,"获取发布历史失败");
            });
        }
    },
    componentDidMount: function () {
        //监听所有可能的界面事件 添加订阅
        var that = this;
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.order('publish_state_update', function (data) {
                    if(typeof (data.body.msg) == "undefined"){
                        that.componentWillMount();
                    }
                })
            }
        );
        msgFrontAgent.order('product_uploading', function (message) {
            if(message){
                document.getElementById(message.body.publish_id + "state").innerText = "已上传:"+message.body.msg;
            }
        });
    },
    componentWillUnmount: function () {
        msgFrontAgent.onConnected(function () {
                msgFrontAgent.disorder('publish_state_update');
            }
        );

    },
    onItemSelected: function (item, index) {
        this.setState({"selectedIndex": index}, this.renderPublishRec);
    },
    deletePublishRec: function (index, publish_id) {
        this.setState({"selectedIndex": index}, this.renderPublishRec);
        confirm("确定删除？", function () {
            HttpRequest.deletePublish(publish_id).success(function (resp) {
                if (resp.code != 500) {
                    this.componentWillMount();
                } else {
                    toastr.error(null, "删除失败");
                }
            }.bind(this)).error(function () {
                toastr.error(null, "删除失败");
            });
        }.bind(this))
    },
    renderPublishRec: function () {
        var publishRec = [];
        var selectedStyle = {
            backgroundColor: "#f3f3f3",
            opacity: "0.8",
            borderBottom: "#f2f2f2 1px solid",
            height: "50px",
            fontSize: "15px"
        };
        var publish_state = "";
        this.state.publishInfo.map(function (data, index) {

            var style = {borderBottom: "#f2f2f2 1px solid", height: "50px", fontSize: "15px"};

            var img_del = "/res/image/delete.png";
            if (index == this.state.selectedIndex) {
                style = selectedStyle;

                img_del = "/res/image/delete_h.png";
            } else {

                img_del = "/res/image/delete.png"
            }

            switch (data.state) {
                case "publish_created":
                    publish_state = "发布任务发起";
                    break;
                case "publish_failed":
                    publish_state = "发布失败";
                    break;
                case "published":
                    publish_state = "已发布";
                    break;
                case "products_prepared":
                    publish_state = "开始上传产品";
                    break;
                case "uploaded":
                    publish_state = "商品上传成功";
                    break;
                case "upload_failed":
                    publish_state = "商品上传失败";
                    break;
                default:
                    publish_state = "已上传:"+data.state;
                    break;
            }
            publishRec.push(
                <tr id={"table_item_" + index}
                    key = {index}
                    onClick={this.onItemSelected.bind(this,data,index)}
                    style={style}
                >
                    <td style={{cursor:"pointer",paddingLeft:"40px",width:"20%"}}>{index + 1}</td>
                    <td style={{cursor:"pointer",width:"20%"}}>{data.name}</td>
                    <td style={{cursor:"pointer",width:"20%"}}>{data.version}</td>
                    <td style={{cursor:"pointer",width:"20%"}} id = {data._id + "state"}>{publish_state}</td>
                    <td style={{width:"20%"}}>
                        <div>
                            <img
                                src={img_del}
                                onClick={function(){this.deletePublishRec(index,data._id)}.bind(this)}
                                style={{cursor:"pointer",float:"left"}}
                            />

                        </div>
                    </td>
                </tr>
            );
        }.bind(this));
        this.setState({
            publishRec: publishRec
        });
    },
    render: function () {
        var content_pageRight = null;
        if (this.state.publishRec && this.state.publishRec.length > 0) {
            content_pageRight =
                <div style={{height:"100%"}}>
                    <table style={{fontSize:"16px",width:"100%",background:"#ffffff",marginTop:"20px"}}>
                        <tbody>
                        <tr style={{backgroundColor: "#e3e3e3",opacity: "0.8",borderBottom: "#f2f2f2 1px solid",height: "50px",fontSize: "15px"}}>
                            <th style={{paddingLeft:"30px",width:"20%"}}>编号</th>
                            <th style={{width:"20%"}}>名称</th>
                            <th style={{width:"20%"}}>版本</th>
                            <th style={{width:"20%"}}>状态</th>
                            <th style={{width:"20%"}}>操作</th>
                        </tr>
                        </tbody>
                    </table>
                    <div style={{overflowY:"auto", height:"calc(100% - 40px)"}}>
                        <table style={{fontSize:"16px",width:"100%",background:"#ffffff"}}>
                            <tbody>
                            {this.state.publishRec}
                            </tbody>
                        </table>
                    </div>
                </div>
        } else {
            content_pageRight = <div style={{textAlign:"center"}}>
                <div style={{color:"#969696",marginTop:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                    <i className="fa fa-exclamation-circle"
                       style={{fontSize:"48px",cursor:"pointer"}}/>
                    <br/>
                    该项目没有发布记录！
                </div>
            </div>
        }
        return (
            <div style={{width:"100%",height:"100%"}}>
                {content_pageRight}
            </div>
        )
    }
});

